package com.wocloud.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.wocloud.common.BusinessException;
import com.wocloud.constant.LogConstant;
import com.wocloud.constant.RouteBusinessTypeConstant;
import com.wocloud.domain.vo.UrlBusinessVo;
import com.wocloud.domain.wo.*;
import com.wocloud.service.EventResourceInfoService;
import com.wocloud.service.LogEventService;
import com.wocloud.service.LoginInfoService;
import com.wocloud.util.HttpClientUtils;
import com.wocloud.util.RedisUtil;
import com.wocloud.wo.dao.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.net.URL;
import java.util.*;

/**
 * @author wang shaobo
 * @date 2020/7/13  17:08
 */
@Service
public class LogEventServiceImpl implements LogEventService {

    private static final Logger log = LoggerFactory.getLogger(LogEventServiceImpl.class);

    private static final String logInstance = "网关日志";
    private static final String logOrder = "网关订单日志";
    private static final String instancePush = "实例异步推送";
    private static final String orderPush = "订单异步推送";

    //特殊业务类型处理url
    private static final String cust = "cust";
    private static final String workorder = "workorder";
    private static final String product = "product";
    private static final String message = "message";
    private static final String cloudmarket = "cloudmarket";
    private static final String bill = "bill";
    private static final String logmessagekey = "logmessageredis";

    @Autowired
    private EventResourceInfoService eventResourceInfoService;

    @Autowired
    private EventLogMapper eventLogMapper;

    @Autowired
    CustLoginMapper custLoginMapper;

    @Autowired
    LoginInfoService loginInfoService;

    @Autowired
    UcsSubscriptionMapper ucsSubscriptionMapper;

    @Autowired
    OrderInnerItemMapper orderInnerItemMapper;

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private OrderSubItemMapper orderSubItemMapper;

    @Value("${yunjingUrl}")
    private String yunjingUrl;


    /**
     * 校验处理网关的消息
     * @param logMessage
     * @return
     */
    public boolean checkLogMessage(String logMessage){
        if(StringUtils.isEmpty(logMessage)){
            log.info("处理logMessage为空,暂不处理");
            return false;
        }
        try{
            JSONObject messageJson = JSONObject.parseObject(logMessage);
            if ("GET".equalsIgnoreCase(messageJson.getString("method").trim())) {
                log.info("请求为get请求,暂不处理");
                return false;
            }
            if (StringUtils.isEmpty(messageJson.getString("url"))) {
                log.info("请求url为空,暂不处理");
                return false;
            }
            if (messageJson.getJSONObject("params") == null) {
                log.info("请求params为空,暂不处理");
                return false;
            }
            if (messageJson.getJSONObject("response") == null) {
                log.info("response为空,暂不处理");
                return false;
            }
            if ("GET".equals(messageJson.getString("method").trim())) {
                log.info("请求为get请求,暂不处理");
                return false;
            }

        }catch (Exception e){
            log.info("处理logMessage转json有误,暂不处理");
            return false;
        }

        log.info("处理网关消息:"+logMessage);
        return true;
    }

    /**
     * 校验实例异步推送消息
     * @param logMessage
     * @return
     */
    public boolean checkInstanceLogMessage(String logMessage){
        if(StringUtils.isEmpty(logMessage)){
            log.info("处理实例异步logMessage为空,暂不处理");
            return false;
        }
        try{
            JSONObject messageJson = JSONObject.parseObject(logMessage);
            if(StringUtils.isEmpty(messageJson.getString("subscriptionId"))){
                log.info("处理实例异步消息subscriptionId为空,暂不处理");
                return false;
            }
        }catch (Exception e){
            log.info("处理logMessage转json有误,暂不处理");
            return false;
        }

        log.info("处理实例异步推送消息:"+logMessage);

        return true;
    }

    /**
     * 校验订单异步推送消息
     * @param logMessage
     * @return
     */
    public boolean checkOrderLogMessage(String logMessage){
        if(StringUtils.isEmpty(logMessage)){
            log.info("处理实例异步logMessage为空,暂不处理");
            return false;
        }
        try{
            JSONObject messageJson = JSONObject.parseObject(logMessage);
            if(StringUtils.isEmpty(messageJson.getString("masterOrderId"))){
                log.info("处理订单异步消息masterOrderId为空,暂不处理");
                return false;
            }
            if(StringUtils.isEmpty(messageJson.getString("innerOrderId"))){
                log.info("处理订单异步消息innerOrderId为空,暂不处理");
                return false;
            }
        }catch (Exception e){
            log.info("处理logMessage转json有误,暂不处理");
            return false;
        }

        log.info("处理订单异步推送消息:"+logMessage);
        return true;
    }


    /**
     * 网关消息处理
     * @param logMessage
     */
    @Override
    public void dealLogMessageInstance(String logMessage){
        //校验请求参数
        if(!checkLogMessage(logMessage)){
            log.info("网关消息参数有误,暂不处理消息:"+logMessage);
            return;
        }
        long startTime = System.currentTimeMillis();
        JSONObject messageJson = JSONObject.parseObject(logMessage);
        String url = messageJson.getString("url");

        try{
            URL urlT = new URL(url);
            String path = urlT.getPath();
            //需要判断url情况
            int secIndex = path.indexOf("/", path.indexOf("/") + 1);
            String secRoute = path.substring(path.indexOf("/") + 1, secIndex);
            if (cust.equalsIgnoreCase(secRoute) || workorder.equalsIgnoreCase(secRoute) || product.equalsIgnoreCase(secRoute) ||
                    message.equalsIgnoreCase(secRoute) || cloudmarket.equalsIgnoreCase(secRoute) || bill.equalsIgnoreCase(secRoute)) {
                url = path;
            }else{
                url = url.substring(url.lastIndexOf("/", url.lastIndexOf("/") - 1));
            }
        }catch (Exception e){
            log.info("转换url异常");
            url = url.substring(url.lastIndexOf("/", url.lastIndexOf("/") - 1));
        }
        UrlBusinessVo urlBusinessVo = null;
        String rkey = logmessagekey + "_" + url;
        //读取redis缓存获得业务vo
        if(redisUtil.hasKey(rkey)){
            urlBusinessVo = (UrlBusinessVo) redisUtil.getObject(rkey);
            log.info(rkey + ",从redis查询到对应的业务:" + urlBusinessVo.toString());
        }
        if (urlBusinessVo == null) {
            //按照url查询枚举
            RouteBusinessTypeConstant.URL_BUSINESS urlBusiness = RouteBusinessTypeConstant.URL_BUSINESS.getURL_BUSINESSByUrl(url);
            if (urlBusiness == null) {
                log.info(url + ",未查询到对应的业务");
                return;
            }
            log.info(url + ",查询到对应的业务:" + urlBusiness.toString());
            urlBusinessVo = getUrlBussinessVo(urlBusiness);
            //将vo缓存到redis中
            redisUtil.setObject(rkey, urlBusinessVo,60*60*24);
        }

        //判断是否是需要记录多个日志
        if(RouteBusinessTypeConstant.URL_BUSINESS.applicationConfigGroup.getOperateType().equals(urlBusinessVo.operateType)){
            insertEventLogs(messageJson,urlBusinessVo);
            return;
        }
        EventLog eventLog = getEventLog(messageJson, urlBusinessVo);
        insertEventLog(eventLog,logInstance);
        synEventLog(eventLog,logInstance);
        //判断是否为特殊情况,需要解绑绑定双方进行存储
        if (StringUtils.isNotEmpty(urlBusinessVo.getTemp())) {

            log.info(url + ",需要执行其他业务再次存储,其他业务temp:" + urlBusinessVo.getTemp());
            RouteBusinessTypeConstant.URL_BUSINESS businessTemp = RouteBusinessTypeConstant.URL_BUSINESS.getURL_BUSINESSByUrl(urlBusinessVo.getTemp());
            if(businessTemp == null){
                log.info(url + ",查询其他业务为空");
            }
            log.info(url + ",需要执行其他业务:" + businessTemp.toString());
            urlBusinessVo = getUrlBussinessVo(businessTemp);
            EventLog eventLogTemp = getEventLog(messageJson, urlBusinessVo);
            insertEventLog(eventLogTemp,logInstance);
            synEventLog(eventLogTemp,logInstance);
            //存储redis更新的时候需要一起更新
            String bindEventIdRkey = eventLog.getId();
            redisUtil.set(bindEventIdRkey,eventLogTemp.getId(),60*60);
            log.info("绑定解绑二次处理成功");
        }
        log.info("处理网关消息成功结束,处理时间:" + (System.currentTimeMillis() - startTime));


    }


    /**
     * 需要记录多条日志
     * @param messageJson
     * @param urlBusinessVo
     */
    private void insertEventLogs(JSONObject messageJson, UrlBusinessVo urlBusinessVo){

        log.info("处理网关消息体,需要存储多个日志记录");
        JSONObject params = messageJson.getJSONObject("params");
        JSONObject properties = params.getJSONObject("properties");
        if(properties == null){
            log.info("处理网关消息体,properties为空");
        }
        JSONObject response = messageJson.getJSONObject("response");
        String address = messageJson.getString("address");
        Date time = messageJson.getDate("time");

        JSONArray rdsList = properties.getJSONArray("rdsList");
        if(rdsList != null && rdsList.size() > 0){
            String logMessageOperator = loginInfoService.getLogMessageOperator(messageJson);
            for (int i = 0; i < rdsList.size(); i++) {
                JSONObject propertie = (JSONObject) rdsList.get(i);

                EventLog eventLog = new EventLog();
                eventLog.setPlatform(urlBusinessVo.getPlatform());
                eventLog.setModuleCode(urlBusinessVo.getModuleCode());
                eventLog.setModuleName(urlBusinessVo.getModuleName());
                eventLog.setOperateType(urlBusinessVo.getOperateType());
                eventLog.setOperateDesc(urlBusinessVo.getOperateDesc());
                eventLog.setOperator(logMessageOperator);
                eventLog.setOperateTime(time);

                eventResourceInfoService.setResourceInfo(properties, response, eventLog, urlBusinessVo);

                insertEventLog(eventLog,logInstance);
                synEventLog(eventLog,logInstance);

            }
        }
    }


    /**
     * 获得eventlog实体
     * @param urlBusinessVo
     * @return
     */
    public EventLog getEventLog(JSONObject messageJson,UrlBusinessVo urlBusinessVo){
        log.info("处理网关消息体,封装获得日志实体对象");
        JSONObject params = messageJson.getJSONObject("params");
        JSONObject properties = params.getJSONObject("properties");
        if(properties == null){
            log.info("处理网关消息体,properties为空");
        }
        JSONObject response = messageJson.getJSONObject("response");
        String address = messageJson.getString("address");
        Date time = messageJson.getDate("time");

        EventLog eventLog = new EventLog();
        eventLog.setPlatform(urlBusinessVo.getPlatform());
        eventLog.setModuleCode(urlBusinessVo.getModuleCode());
        eventLog.setModuleName(urlBusinessVo.getModuleName());
        eventLog.setOperateType(urlBusinessVo.getOperateType());
        eventLog.setOperateDesc(urlBusinessVo.getOperateDesc());
        eventLog.setOperateTime(time);
        eventLog.setOperator(loginInfoService.getLogMessageOperator(messageJson));

        if (response.getInteger("code") == LogConstant.ResponseCode.SUCCESS.getCode()) {
            eventLog.setOperateStatus(LogConstant.ResponseCode.SUCCESS.getMsg());
        }else{
            eventLog.setOperateStatus(LogConstant.ResponseCode.FAIL.getMsg());
        }
        eventLog.setOperateAddress(address.substring(address.indexOf("/") + 1, address.lastIndexOf(":")));
        eventResourceInfoService.setResourceInfo(properties, response, eventLog, urlBusinessVo);
        log.info("处理网关消息,封装eventLog:"+JSONObject.toJSONString(eventLog));
        return eventLog;

    }

    /**
     * 将枚举信息转vo
     * @param urlBusiness
     */
    private UrlBusinessVo getUrlBussinessVo(RouteBusinessTypeConstant.URL_BUSINESS urlBusiness){
        //将信息封装到vo中
        UrlBusinessVo urlBusinessVo = new UrlBusinessVo();
        urlBusinessVo.setUrl(urlBusiness.getUrl());
        urlBusinessVo.setPlatform(urlBusiness.getPlatform());
        urlBusinessVo.setModuleCode(urlBusiness.getModuleCode());
        urlBusinessVo.setModuleName(urlBusiness.getModuleName());
        urlBusinessVo.setOperateDesc(urlBusiness.getOperateDesc());
        urlBusinessVo.setOperateType(urlBusiness.getOperateType());
        urlBusinessVo.setResourceNameField(urlBusiness.getResourceNameField());
        urlBusinessVo.setResourceIdField(urlBusiness.getResourceIdField());
        urlBusinessVo.setResourceIdSecField(urlBusiness.getResourceIdSecField());
        urlBusinessVo.setTemp(urlBusiness.getTemp());
        urlBusinessVo.setResourceName(urlBusiness.getResourceName());
        urlBusinessVo.setResourceId(urlBusiness.getResourceId());
        urlBusinessVo.setUcsSubsFlag(urlBusiness.isUcsSubsFlag());
        return urlBusinessVo;

    }



    /**
     * 处理网关发送来的订单请求记录日志
     * @param logMessage
     */
    @Override
    public void dealLogMessageOrder(String logMessage) {
        log.info("处理网关订单消息:"+logMessage);
        long startTime = System.currentTimeMillis();
        EventLog eventLog = new EventLog();
        JSONObject params = new JSONObject();
        JSONObject messageJson = JSONObject.parseObject(logMessage);
        JSONObject response = messageJson.getJSONObject("response");
        String url = messageJson.getString("url");
        //通过枚举获得该请求的信息
        RouteBusinessTypeConstant.URL_MASTERORDER url_masterorder = RouteBusinessTypeConstant.handleUrlMasterorder(url);
        if (url_masterorder != null) {
            //获取操作者信息
            eventLog.setOperator(loginInfoService.getLoginNameParams(messageJson));
            //获取订单业务信息
            eventLog.setPlatform(url_masterorder.getPlatform());
            eventLog.setOperateDesc(url_masterorder.getOperateDesc());
            eventLog.setOperateType(url_masterorder.getOperateType());

            if (response.getInteger("code") == LogConstant.ResponseCode.SUCCESS.getCode()) {

                eventLog.setOperateStatus(LogConstant.ResponseCode.SUCCESS.getMsg());
            } else {
                eventLog.setOperateStatus(LogConstant.ResponseCode.FAIL.getMsg());
            }
            String address = messageJson.getString("address");
            eventLog.setOperateAddress(address.substring(address.indexOf("/") + 1, address.lastIndexOf(":")));
            eventLog.setOperateTime(new Date());
            if (eventLog.getPlatform().trim().equals("console")) {
                eventLog.setResourceOwner(eventLog.getOperator());
            }
            //获得该订单的masterOrderId后后面订单异步通过主订单id
            if (response.get("result") != null) {
                eventLog.setMasterOrderId(response.getString("result"));
            }
            //存储并同步日志记录
            insertEventLog(eventLog,logOrder);
            synEventLog(eventLog,logOrder);
        } else {
            log.info("网关订单请求url:" + url + ",未查询到业务类型");
        }
        log.info("处理网关订单消息成功结束,处理时间:" + (System.currentTimeMillis() - startTime));

    }


    /**
     * 异步推送实例日志处理
     * @param logMessage
     */
    @Override
    public void dealInstanceLogMessage(String logMessage) {
        if(!checkInstanceLogMessage(logMessage)){
            log.info("实例异步推送消息有误,暂不处理消息:"+logMessage);
            return;
        }
        long startTime = System.currentTimeMillis();
        EventLog eventLog = new EventLog();
        JSONObject messageJson = JSONObject.parseObject(logMessage);
        String serviceNum = "";
        String subsId = "";
        if (messageJson.get("serviceNum") != null) {
            serviceNum = messageJson.getString("serviceNum");
        }
        subsId = messageJson.getString("subscriptionId");
        //获取实例信息
        UcsSubscriptionExample ucsSubscriptionExample = new UcsSubscriptionExample();
        UcsSubscriptionExample.Criteria ucsSubscriptionExampleCriteria = ucsSubscriptionExample.createCriteria();
        ucsSubscriptionExampleCriteria.andSubscriptionIdEqualTo(Integer.valueOf(subsId));
        List<UcsSubscription> ucsSubscriptions = ucsSubscriptionMapper.selectByExample(ucsSubscriptionExample);
        if (ucsSubscriptions == null || ucsSubscriptions.size() < 1) {
            log.info("通过subsId未查询到值,subsId:" + subsId);
            return;
        }
        EventLogExample example = new EventLogExample();
        EventLogExample.Criteria criteria = example.createCriteria();
        criteria.andSubscriptionIdEqualTo(subsId);
        criteria.andMasterOrderIdIsNull();
        example.setOrderByClause("operate_time");
        List<EventLog> eventLogBySubsId = eventLogMapper.selectByExample(example);
        if (eventLogBySubsId.size() > 0) {
            EventLog eventLogUpdate = eventLogBySubsId.get(0);
            log.info("获得eventLogUpdate对象信息:" + JSONObject.toJSONString(eventLogUpdate));
            //对更新的对象先判断是否有值
            if(StringUtils.isEmpty(eventLogUpdate.getResourceId())){
                //默认先存储异步来的serviceNum
                eventLogUpdate.setResourceId(serviceNum);
            }
            String operateStatus = LogConstant.ResponseCode.SUCCESS.getMsg();
            if (!Integer.valueOf(LogConstant.ResponseCode.SUCCESS.getCode()).equals(messageJson.get("code"))) {
                operateStatus = LogConstant.ResponseCode.FAIL.getMsg();
            }
            eventLogUpdate.setOperateStatus(operateStatus);

            log.info("OperateType: " + eventLogUpdate.getOperateType());
            if (!"detachNetCard".equals(eventLogUpdate.getOperateType())) {
                UcsSubscription ucsSubscription = ucsSubscriptions.get(0);
                log.info("查询ucsSubscription对象信息:" + JSONObject.toJSONString(ucsSubscription));
                if (StringUtils.isEmpty(eventLogUpdate.getResourceId()) && StringUtils.isNotEmpty(ucsSubscription.getServiceNum())) {
                    eventLogUpdate.setResourceId(ucsSubscription.getServiceNum());
                }
                if (StringUtils.isEmpty(eventLogUpdate.getResourceName()) && StringUtils.isNotEmpty(ucsSubscription.getSubscriptionName())) {
                    eventLogUpdate.setResourceName(ucsSubscription.getSubscriptionName());
                }
                if (StringUtils.isEmpty(eventLogUpdate.getCloudRegion()) && StringUtils.isNotEmpty(ucsSubscription.getCloudId())) {
                    eventLogUpdate.setCloudRegion(ucsSubscription.getCloudId());
                }
            }

            //按照id进行更新
            EventLogExample exampleUpdateTemp = new EventLogExample();
            EventLogExample.Criteria criteriaUpdateTemp = exampleUpdateTemp.createCriteria();
            criteriaUpdateTemp.andIdEqualTo(eventLogUpdate.getId());
            log.info("更新eventlog对象信息:" + JSONObject.toJSONString(eventLogUpdate));
            eventLogMapper.updateByExampleSelective(eventLogUpdate, exampleUpdateTemp);
            synEventLog(eventLogUpdate,instancePush);

            //判断是否有特殊情况,解绑绑定一条消息存储两个日志的,如果有将绑定的消息获取出来,主要同步状态
            String rkey = eventLogUpdate.getId();
            if(redisUtil.hasKey(rkey)) {
                String idTemp = (String) redisUtil.get(rkey);
                EventLogExample exampleTemp = new EventLogExample();
                EventLogExample.Criteria criteriaTemp = exampleTemp.createCriteria();
                criteriaTemp.andIdEqualTo(idTemp);
                List<EventLog> eventLogById = eventLogMapper.selectByExample(exampleTemp);
                if (eventLogById != null && eventLogById.size() > 0) {
                    EventLog eventLogTemp = eventLogById.get(0);
                    eventLogTemp.setOperateStatus(operateStatus);
                    log.info("更新eventlog绑定对象信息:" + JSONObject.toJSONString(eventLogTemp));
                    eventLogMapper.updateByExampleSelective(eventLogTemp, exampleTemp);
                    synEventLog(eventLogTemp, instancePush);
                }
            }

        }
        log.info("处理实例异步推送消息成功结束,处理时间:" + (System.currentTimeMillis() - startTime));
    }


    /**
     * 处理订单异步发送的消息单日志处理
     * @param logMessage
     */
    @Override
    public void dealOrderLogMessage(String logMessage){
        if(!checkOrderLogMessage(logMessage)){
            log.info("订单异步推送消息有误,暂不处理消息:"+logMessage);
            return;
        }
        long startTime = System.currentTimeMillis();
        JSONObject messageJson = JSONObject.parseObject(logMessage);
        String masterOrderId = messageJson.getString("masterOrderId");
        String innerOrderId = messageJson.getString("innerOrderId");
        //获取下订单产生日志信息，operateType,address,status,operateDesc
        EventLogExample eventLogExample = new EventLogExample();
        EventLogExample.Criteria eventCriteria = eventLogExample.createCriteria();
        eventCriteria.andMasterOrderIdEqualTo(masterOrderId);
        eventCriteria.andInnerOrderIdIsNull();
        List<EventLog> logList = eventLogMapper.selectByExample(eventLogExample);
        if (logList.size() > 0) {
            //查询order_inner_item获取实例id,resourceType
            OrderInnerItemExample example = new OrderInnerItemExample();
            OrderInnerItemExample.Criteria orderCriteria = example.createCriteria();
            orderCriteria.andInnerOrderIdEqualTo(innerOrderId);
            //按照is_master排序
            example.setOrderByClause("is_master desc");
            List<OrderInnerItem> list = orderInnerItemMapper.selectByExample(example);
            boolean conBwp = false;
            if (RouteBusinessTypeConstant.URL_MASTERORDER.SUBMIT_UPGRADE_ORDER.getOperateType().equals(logList.get(0).getOperateType())) {
                //只有升配要判断
                conBwp = upgradeOrderConBwp(list);
            }
            boolean eipFlag = true;
            int count = list.size();
            int countTemp = count;
            //定义临时日志对象,用用于增加eip升配日志记录
            EventLog eventLogTemp = new EventLog();
            for (int i = 0; i < count; i++) {
                EventLog eventLog = new EventLog();
                eventLog.setMasterOrderId(masterOrderId);
                eventLog.setInnerOrderId(innerOrderId);
                eventLog.setOperateDesc(logList.get(0).getOperateDesc());
                Integer resourceType;
                String resourceId = "";
                String cloudRegion = "";
                Date createDate = new Date();
                if(i < countTemp){
                    resourceType = list.get(i).getResourceType();
                    resourceId = list.get(i).getResourceId();
                    createDate = list.get(i).getCreateDate();
                    cloudRegion = list.get(i).getPool();
                }else{
                    if(eipFlag){
                        continue;
                    }
                    //需要额外增加存储的时候
                    resourceType = RouteBusinessTypeConstant.OrderResourceType.eip.getResourceType();
                    resourceId = eventLogTemp.getResourceId();
                    createDate = eventLogTemp.getOperateTime();
                    cloudRegion = eventLogTemp.getCloudRegion();
                }
                //判断主资源是否是EIP
                if(conBwp && i == 0 && RouteBusinessTypeConstant.OrderResourceType.eip.getResourceType() != resourceType.intValue()){
                    count += 1;
                }
                //如果主资源不是eip需要从公网带宽的订单信息中获取，并增加记录一条日志
                if(conBwp && RouteBusinessTypeConstant.OrderResourceType.bwp.getResourceType() == resourceType.intValue()){
                    OrderInnerItem orderInnerItem = orderInnerItemMapper.selectByPrimaryKey(list.get(i).getInnerOrderItemId());
                    String resourceConfiguration = orderInnerItem.getResourceConfiguration();
                    JSONObject jsonObject = JSONObject.parseObject(resourceConfiguration);
                    String eipId = jsonObject.getString("floatIpId");
                    if(StringUtils.isEmpty(eipId)){
                        //不确定订单那里传参,判断两次获得eipId
                        eipId = jsonObject.getString("vipId");
                    }
                    if(StringUtils.isNotEmpty(eipId)){
                        eventLogTemp.setResourceId(eipId);
                        eventLogTemp.setOperateTime(list.get(i).getCreateDate());
                        eventLogTemp.setCloudRegion(list.get(i).getPool());
                        eipFlag = false;
                    }
                }
                if(resourceType != null){
                    RouteBusinessTypeConstant.OrderResourceType orderResourceType = RouteBusinessTypeConstant.OrderResourceType.getOrderResourceType(resourceType);
                    if(orderResourceType != null){
                        eventLog.setModuleCode(orderResourceType.getModuleCode());
                        eventLog.setModuleName(orderResourceType.getModuleName());
                        //只有块存储升配操作名称改为扩容
                        if (RouteBusinessTypeConstant.URL_MASTERORDER.SUBMIT_UPGRADE_ORDER.getOperateType().equals(logList.get(0).getOperateType())) {
                            if(RouteBusinessTypeConstant.OrderResourceType.volume.getResourceType() == resourceType.intValue()){
                                eventLog.setOperateDesc("扩容");
                            }
                        }
                        //只有云服务器创建的时候区分gpu
                        if (RouteBusinessTypeConstant.URL_MASTERORDER.SUBMIT_NEW_PURCHASE_ORDER.getOperateType().equals(logList.get(0).getOperateType())) {
                            if(RouteBusinessTypeConstant.OrderResourceType.gpu.getResourceType() == resourceType.intValue()){
                                eventLog.setOperateDesc("创建gpu");
                            }
                        }
                        //RDS需要根据请求的resourceConfig来判断具体操作类型
                        if(RouteBusinessTypeConstant.OrderResourceType.rds.getResourceType() == resourceType.intValue()){
//                            orderInnerItemMapper.getClass().
//                            getRdsOperateType(list.get(i));

                        }


                    }
                }
                //查询ucs_subscription获取实例name,regionId
                UcsSubscriptionExample ucsSubscriptionExample = new UcsSubscriptionExample();
                UcsSubscriptionExample.Criteria ucsSubscriptionExampleCriteria = ucsSubscriptionExample.createCriteria();
                ucsSubscriptionExampleCriteria.andServiceNumEqualTo(resourceId);
                List<UcsSubscription> ucsSubscriptions = ucsSubscriptionMapper.selectByExample(ucsSubscriptionExample);
                if (ucsSubscriptions.size() > 0) {
                    eventLog.setSubscriptionId(ucsSubscriptions.get(0).getSubscriptionId().toString());
                    eventLog.setResourceName(ucsSubscriptions.get(0).getSubscriptionName());
                    eventLog.setCloudRegion(ucsSubscriptions.get(0).getCloudId());
                }
                eventLog.setOperateTime(createDate);
                eventLog.setResourceId(resourceId);
                eventLog.setCloudRegion(cloudRegion);
                eventLog.setOperator(logList.get(0).getOperator());
                eventLog.setPlatform(logList.get(0).getPlatform());
                eventLog.setOperateType(logList.get(0).getOperateType());
                eventLog.setOperateStatus(logList.get(0).getOperateStatus());
                eventLog.setOperateAddress(logList.get(0).getOperateAddress());

                insertEventLog(eventLog,orderPush);
                synEventLog(eventLog,orderPush);
            }
        }

        log.info("处理订单异步推送消息成功结束,处理时间:" + (System.currentTimeMillis() - startTime));

    }


    /**
     * 判读是否为公网带宽升级
     * @param list
     * @return
     */
    private boolean upgradeOrderConBwp(List<OrderInnerItem> list) {
        for (int i = 0; i < list.size(); i++) {
            if (RouteBusinessTypeConstant.OrderResourceType.bwp.getResourceType() == list.get(i).getInstanceType().intValue()) {
                return true;
            }
        }

        return false;
    }


    private void insertLogs(){

    }

    /**
     * 查询子订单项,根据请求参数获得rds操作类型
     * @param orderSubId
     * @param orderType
     * @return
     */
    private Map<String,String> getRdsOperateType(String orderSubId,Integer orderType){
        Map<String,String> map = new HashMap<String,String>(2);
        String operateType = "";
        String operateDesc = "";
        String configuration = orderSubItemMapper.queryOrderSubItemConfigBySubId(orderSubId);
        if(StringUtils.isEmpty(configuration) || orderType == null){
            log.info(orderPush+",子订单项未获得请求配置信息,子订单项号："+orderSubId);
        }
        JSONObject jsonObject = JSONObject.parseObject(configuration);
        //根据请求配置判断rds操作具体类型
        int orderTypeNew = 1;
        int orderTypeUp = 2;
        //只有订单类型为1的时候进行判断
        if(StringUtils.isNotEmpty(jsonObject.getString("backupId")) && orderType.intValue() == orderTypeNew){
            operateType = "recoverRdsBackup";
            operateDesc = "恢复备份";
        }
        if(orderTypeUp == orderType.intValue()){
            if (StringUtils.isNotEmpty(jsonObject.getString("flavorId"))) {
                operateType = "specModify";
                operateDesc = "规格变更";
            } else if (StringUtils.isNotEmpty(jsonObject.getString("storageSize"))) {
                operateType = "storageExpansion";
                operateDesc = "云盘扩容";
            } else if (StringUtils.isNotEmpty(jsonObject.getString("boughtBackupSize"))) {
                operateType = "backupExpansion ";
                operateDesc = "备份空间扩容";
            }
        }
        map.put("operateType",operateType);
        map.put("operateDesc",operateDesc);

        return map;
    }







    /**
     * 获得对象主键id
     *
     * @param eventLog
     * @return
     */
    public synchronized void insertEventLog(EventLog eventLog,String businessType) {
        eventLog.setId(UUID.randomUUID().toString());
        try {
            int insert = eventLogMapper.insert(eventLog);
            log.info(businessType + ",记录日志记录成功,记录" + insert + "条,日志信息:" + JSONObject.toJSONString(eventLog));
        } catch (Exception e) {
            log.info(businessType + ",记录日志记录失败,日志信息:" + JSONObject.toJSONString(eventLog));
        }
    }


    /**
     * 同步日志到云警系统
     * @param eventLog
     */
    public void synEventLog(EventLog eventLog,String businessType){

        JSONObject objSyn = new JSONObject();
        objSyn.put("id", eventLog.getId());
        objSyn.put("operator", eventLog.getOperator());
        objSyn.put("operateAddress", eventLog.getOperateAddress());
        objSyn.put("platformCode",eventLog.getPlatform());
        objSyn.put("moduleCode",eventLog.getModuleCode());
        objSyn.put("moduleName",eventLog.getModuleName());
        objSyn.put("operatorCode",eventLog.getOperateType());
        objSyn.put("operateDesc",eventLog.getOperateDesc());
        objSyn.put("operatorName",eventLog.getOperateDesc());
        objSyn.put("operateResult",eventLog.getOperateStatus());
        objSyn.put("cloudRegion",eventLog.getCloudRegion());
        objSyn.put("resourceName",eventLog.getResourceName());
        objSyn.put("resourceId", eventLog.getResourceId());
        objSyn.put("resourceOwner",eventLog.getResourceOwner());
        objSyn.put("operateTime",eventLog.getOperateTime());
//        String results = HttpClientUtils.httpPost("http://"+yunjingUrl+"/operatelog/putLog", JSONObject.parseObject(JSONObject.toJSON(eventLog).toString()));

        String results = HttpClientUtils.httpPost("http://"+yunjingUrl+"/operatelog/putLog", objSyn);
        if (results == null || results.isEmpty() || JSONObject.parseObject(results).getInteger("code") != LogConstant.ResponseCode.SUCCESS.getCode()) {
            log.info(businessType+",同步日志记录失败,日志信息:"+JSONObject.toJSONString(eventLog));
            throw new BusinessException("同步操作日志失败");
        }else{
            log.info(businessType+",同步日志记录成功,日志信息:"+JSONObject.toJSONString(eventLog));
        }

    }


}
